package com.woniuxy.bookmall.service;

import com.woniuxy.bookmall.utils.RedisUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.stereotype.Service;
import org.yaml.snakeyaml.scanner.ScannerImpl;

import java.util.Random;
import java.util.concurrent.TimeUnit;

@Service
public class EmailService {

    @Autowired
    JavaMailSender javaMailSender ;

    @Autowired
    RedisUtils redisUtils ;

    /**
     *
     * @param from
     *            发送方
     * @param to
     *            接收方
     * @param subject
     *            主题
     * @param text
     *            内容
     */
    public String sendEmail(String from, String to, String subject, String text){
        try {
            SimpleMailMessage  message = new SimpleMailMessage();
            message.setFrom(from);
            message.setTo(to);
            message.setSubject(subject);
            message.setText(text);

            javaMailSender.send(message);
            return "ok" ;
        }catch (Exception e){
            e.printStackTrace();
            return "NoOk" ;
        }
    }

    public String sendEmail(String fromEmail, String toEmail){
        try {
            SimpleMailMessage  message = new SimpleMailMessage();
            message.setFrom(fromEmail);
            message.setTo(toEmail);
            String subject = "注册验证码" ;
            message.setSubject(subject);
            String code = this.validateCode();
            message.setText("您的验证码是 :"+code);
            javaMailSender.send(message);
            //存储rendis
            redisUtils.set(toEmail,code,120);
            return code ;
        }catch (Exception e){
            e.printStackTrace();
            return "NoOk" ;
        }
    }

    private String validateCode(){
        String data = "0123456789" ;
        String str = "";
        Random random = new Random();
        for (int i=0;i<6;i++){
            //获取 0 --9 随机数
            int k = random.nextInt(10);
            str += data.charAt(k);
        }
        return str ;
    }

    /*public static void main(String[] args) {
        String s = validateCode();
        System.out.println(s);
    }*/
}
